package com.doubi.controller;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.doubi.entity.*;
import com.doubi.service.*;
import io.minio.MinioClient;
import io.minio.ObjectWriteResponse;
import io.minio.PutObjectArgs;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

@RestController
@CrossOrigin("*")
public class ReleasetableController {
    @Autowired
    private ReleasetableService releasetableService;
    @Autowired
    private ReleasevideosService releasevideosService;
    @Autowired
    MinioClient minioClient;
    @Autowired
    private LiketableService liketableService;
    @Autowired
    private HistoryService historyService;
    @Autowired
    public FriendService friendService;
    @Autowired
    private CommenttableService commenttableService;
    /**
     * 视频上传
     */
    @PostMapping("upfile")
    public Map updateImg(@RequestParam("file") MultipartFile file) throws Exception{
        Map map=new HashMap<>();
        String fileName= UUID.randomUUID() +file.getOriginalFilename();//上传文件名
        InputStream inputStream = file.getInputStream();
        ObjectWriteResponse bjectWriteResponse = minioClient.putObject(PutObjectArgs.builder()
                .bucket("star")
                .object(fileName)
                .stream(inputStream, -1L, 10485760L)
                .build());
        //new ResponseEntity().addDate("frilmsg",bjectWriteResponse.object());
        map.put("frilmsg",bjectWriteResponse.object());
        return map;
    }

    /**
     * 查询用户作品集
     * @param userId 用户id
     * @return 视频集合
     */
    @GetMapping("selMyRelease")
    public List<Releasetable> selMyRelease(Integer userId,Integer fid) {
        QueryWrapper<Releasetable> qw=new QueryWrapper<>();
        qw.eq("userId",fid==null?userId:fid).orderByDesc("releaseTime");
        List<Releasetable> list = releasetableService.list(qw);
        for(Releasetable releasetable:list){
            //查询点赞数
            releasetable.setLikeNum(liketableService.releaseCountLike(releasetable.getReleaseId()));
            //查询视频评论数
            releasetable.setCommentNum(commenttableService.countByRid(releasetable.getReleaseId()));
            releasetable.setWorksCover("http://192.168.43.92:9000/star/"+releasetable.getWorksCover());
            //查询当前作品是否被点赞
            QueryWrapper<Inform.Liketable> qwlike = new QueryWrapper<>();
            qwlike.eq("releaseId", releasetable.getReleaseId()).and(i->i.eq("userId", userId));
            Inform.Liketable ifLike = liketableService.getOne(qwlike);
            if(ifLike!=null){
                releasetable.setIfLike(true);
            }

        }
        return list;
    }
    /**
     * 查询我的喜欢
     */
    @GetMapping("selectMyLike")
    public List<Releasetable> selectMyLike(Integer uid,Integer fid) {
        List<Releasetable> rleasetablelist = new ArrayList<>();
        //查询我所有的喜欢
        QueryWrapper<Inform.Liketable> qw=new QueryWrapper<>();
        qw.eq("userId",fid==null?uid:fid).orderByDesc("likeTime");
        List<Inform.Liketable> list = liketableService.list(qw);
        //根据我喜欢的视频id查询id信息
        for (Inform.Liketable liketable : list) {
            QueryWrapper<Releasetable> qw1=new QueryWrapper<>();
            qw1.eq("releaseId",liketable.getReleaseId());
            List<Releasetable> releasetable = releasetableService.list(qw1);
            //根据视频id查询喜欢数
            for(Releasetable video:releasetable){
                //查询点赞数
                video.setLikeNum(liketableService.releaseCountLike(video.getReleaseId()));
                video.setWorksCover("http://localhost:9000/star/"+video.getWorksCover());
                //查询当前作品是否被点赞
                QueryWrapper<Inform.Liketable> qwlike = new QueryWrapper<>();
                qwlike.eq("releaseId", video.getReleaseId()).and(i->i.eq("userId", uid));
                Inform.Liketable ifLike = liketableService.getOne(qwlike);
                if(ifLike!=null){
                    video.setIfLike(true);
                }
                rleasetablelist.add(video);
            }
        }
        return rleasetablelist;
    }
    /**
     * 查询我的历史
     */
    @GetMapping("selectMyHistroy")
    public List<Releasetable> selectMyHistroy(Integer uid,Integer fid) {
        List<Releasetable> rleasetablelist = new ArrayList<>();
        //根据uid查询历史
        QueryWrapper<History> qw=new QueryWrapper<>();
        qw.eq("userId",fid==null?uid:fid).orderByDesc("viewingTime");
        List<History> list = historyService.list(qw);
        for (History history : list) {
            //根据历史记录查询视频信息
            QueryWrapper<Releasetable> qw1=new QueryWrapper<>();
            qw1.eq("releaseId",history.getReleaseId());
            List<Releasetable> releasetable = releasetableService.list(qw1);
            //根据视频id查询喜欢数
            for(Releasetable video:releasetable){
                //查询点赞数
                video.setLikeNum(liketableService.releaseCountLike(video.getReleaseId()));
                video.setWorksCover("http://localhost:9000/star/"+video.getWorksCover());
                //查询当前作品是否被点赞
                QueryWrapper<Inform.Liketable> qwlike = new QueryWrapper<>();
                qwlike.eq("releaseId", video.getReleaseId()).and(i->i.eq("userId", uid));
                Inform.Liketable ifLike = liketableService.getOne(qwlike);
                if(ifLike!=null){
                    video.setIfLike(true);
                }
                rleasetablelist.add(video);
            }
        }
        return rleasetablelist;
    }
    /**
     * 获得单个视频信息
     */
    @PostMapping("getViode")
    public Object getViode(Integer releaseId) {
        QueryWrapper<Releasetable> qw=new QueryWrapper<>();
        qw.eq("releaseId",releaseId);
        Releasetable release = releasetableService.getOne(qw);
        release.setWorksCover("http://localhost:9000/star/"+release.getWorksCover());
        release.setReleaseTime(release.getReleaseTime().substring(5,10));
        //查询评论数
        Integer num=commenttableService.getLastCommentCount(release.getReleaseId());
        release.setCommentNum(num);
        return release;
    }
    /**
     * 发布视频
     */
    @PostMapping("uploadViode")
    public Object uploadViode(@RequestBody Releasetable releaseTable) throws Exception{
        Random r=new Random();//随机生成视频编号
        int i = r.nextInt(9999999);
        releaseTable.setReleaseNum("s"+i);
        LocalDateTime localDateTime=LocalDateTime.now();
        DateTimeFormatter formatter=DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm:ss");
        String data=formatter.format(localDateTime);
        releaseTable.setReleaseTime(data);
        boolean save = releasetableService.save(releaseTable);
        QueryWrapper<Releasetable> qw1=new QueryWrapper<>();
        qw1.eq("releaseTime",data);
        Releasetable releasetable = releasetableService.getOne(qw1);
        int releaseId = releasetable.getReleaseId();
        if(save){
            if(releaseTable.getWorksType()==0){
                //查询视频
                QueryWrapper qw=new QueryWrapper();
                qw.eq("releaseNum",releaseTable.getReleaseNum());
                Releasetable one = releasetableService.getOne(qw);
                Releasevideos releasevideos=new Releasevideos();
                releasevideos.setReleaseId(one.getReleaseId());
                releasevideos.setVideosSrc(releaseTable.getFrilmsg());
                releasevideosService.save(releasevideos);
                return releaseId;
            }
            return "201";
        }
        return false;
    }
    /**
     * 查询视频
     */
    @PostMapping("selectMyVoide")
    public Object selectMyVoide(Integer releaseId){
        QueryWrapper<Releasevideos> qw=new QueryWrapper<>();
        qw.eq("releaseId",releaseId);
        Releasevideos one = releasevideosService.getOne(qw);
        if(one!=null){
            one.setVideosSrc("http://localhost:9000/star/"+one.getVideosSrc());
        }
        return one;
    }

    /**
     * 添加播放量并且添加到历史记录里
     * @param releaseId 视频id
     * @param userId 用户id
     * @return
     */
    @GetMapping("addviwe")
    public Object addviewCount(Integer releaseId,Integer userId){
        //查询是否有浏览记录
        QueryWrapper<History> historyQw=new QueryWrapper<>();
        historyQw.eq("releaseId",releaseId).eq("userId",userId);
        History history = historyService.getOne(historyQw);
        History historyAdd=new History();
        historyAdd.setReleaseId(releaseId);
        historyAdd.setUserId(userId);
        LocalDateTime localDateTime=LocalDateTime.now();
        DateTimeFormatter formatter=DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm:ss");
        String data=formatter.format(localDateTime);
        historyAdd.setViewingTime(data);
        if(history==null){
            historyService.save(historyAdd);
        }else {
            historyAdd.setId(history.getId());
            historyService.updateById(historyAdd);
        }
        QueryWrapper<Releasetable> qw1=new QueryWrapper<>();
        qw1.eq("releaseId",releaseId);
        Releasetable video = releasetableService.getOne(qw1);
        //加一次播放量
        return releasetableService.addviewCounts(video.getViewCounts()+1,video.getReleaseId());
    }

    /**
     * 用户搜索
     */
    @GetMapping("searchViode")
    public Object searchViode(String searhMag,Integer type){
        QueryWrapper<Releasetable> qw=new QueryWrapper<>();
        if(type==0){
            //最多观看
            qw.like("title","%"+searhMag+"%").orderBy(true,false,"viewCounts");
        }else if(type==1){
            //最新发布
            qw.like("title","%"+searhMag+"%").orderBy(true,false,"releaseTime");
        }else {
            //最多喜欢
            qw.like("title","%"+searhMag+"%").orderBy(true,false,"releaseTime");
            List<Releasetable> listviode = releasetableService.list(qw);
            for(Releasetable releasetable:listviode){
                QueryWrapper<Releasevideos> qw1=new QueryWrapper<>();
                releasetable.setWorksCover("http://localhost:9000/star/"+releasetable.getWorksCover());
                qw1.eq("releaseId",releasetable.getReleaseId());
                Releasevideos video = releasevideosService.getOne(qw1);
                if(video!=null){
                    video.setVideosSrc("http://localhost:9000/star/"+video.getVideosSrc());
                    releasetable.setFrilmsg(video.getVideosSrc());
                }
                int i = liketableService.releaseCountLike(releasetable.getReleaseId());
                releasetable.setLikeNum(i);
            }
            int j=listviode.size();
            if(listviode.size()>=2){
                for(int i=0;i<j-1;i++){
                    for (int n=0;n<j-1-i;n++){
                        if (listviode.get(n).getLikeNum()<listviode.get(n+1).getLikeNum()){
                            Releasetable r= listviode.get(n);
                            listviode.set(n,listviode.get(n+1));
                            listviode.set(n+1,r);
                        }
                    }
                }
            }

            return listviode;
        }
        List<Releasetable> listviode = releasetableService.list(qw);
        for(Releasetable releasetable:listviode){
            QueryWrapper<Releasevideos> qw1=new QueryWrapper<>();
            releasetable.setWorksCover("http://localhost:9000/star/"+releasetable.getWorksCover());
            qw1.eq("releaseId",releasetable.getReleaseId());
            Releasevideos video = releasevideosService.getOne(qw1);
            if(video!=null){
                video.setVideosSrc("http://localhost:9000/star/"+video.getVideosSrc());
                releasetable.setFrilmsg(video.getVideosSrc());
            }
        }
        return listviode;
    }

    /**
     * 数据中心我的作品排序
     * @param map list我的作品集合 sortType排序依据
     * @return 排序后的作品集合
     */
    @PostMapping("/sortMyRelease")
    public List<Releasetable> sortMyRelease(@RequestBody Map<String,Object> map){
        List<Releasetable> releasetableList=(List<Releasetable>)map.get("list");
        List<Releasetable> list=new ArrayList<>();
        String sortType=map.get("sortType").toString();
        //尝试排序
        for (Object o:releasetableList) {
            //将list数据转换成json字符串
            String jsonObject = JSON.toJSONString(o);
            //将json转换成需要的对象
            Releasetable releasetable=JSON.parseObject(jsonObject,Releasetable.class);
            list.add(releasetable);
        }
        if (sortType.equals("releaseTime")){
            list.sort(Comparator.comparing(Releasetable::getReleaseTime).reversed());
        }else if (sortType.equals("viewCounts")){
            list.sort(Comparator.comparing(Releasetable::getViewCounts).reversed());
        }else if (sortType.equals("forwardNum")){
            list.sort(Comparator.comparing(Releasetable::getForwardNum).reversed());
        }else if (sortType.equals("likeNum")) {
            list.sort(Comparator.comparing(Releasetable::getLikeNum).reversed());
        }else if (sortType.equals("commentNum")){
            list.sort(Comparator.comparing(Releasetable::getCommentNum).reversed());
        }
        return list;
    }

    /**
     * 分类我的作品
     * @param map
     * @return
     */
    @PostMapping("/sortByClassify")
    public List<Releasetable> sortByClassify(@RequestBody Map<String,Object> map) {
        //分类id
        String classifyId = map.get("classId").toString();
        //用户id
        String userId = map.get("userId").toString();
        List<Releasetable> list = new ArrayList<>();
        if (Integer.parseInt(classifyId) == 0) {
            QueryWrapper<Releasetable> qw = new QueryWrapper<>();
            qw.eq("userId", Integer.parseInt(userId));
            list = releasetableService.list(qw);
        } else {
            QueryWrapper<Releasetable> qw = new QueryWrapper<>();
            qw.eq("userId", Integer.parseInt(userId)).and(i -> i.eq("classId", Integer.parseInt(classifyId)));
            list = releasetableService.list(qw);
        }
        for (Releasetable releasetable : list) {
            //查询点赞数
            releasetable.setLikeNum(liketableService.releaseCountLike(releasetable.getReleaseId()));
            //查询视频评论数
            releasetable.setCommentNum(commenttableService.countByRid(releasetable.getReleaseId()));
            releasetable.setWorksCover("http://localhost:9000/star/" + releasetable.getWorksCover());
        }
        return list;
    }
    /**
     * 查询我的关注
     */
    @GetMapping("attentioninitData")
    public Object attentioninitData(Integer userId){
        //查询我所有的关注
        QueryWrapper<Friend> qw=new QueryWrapper<>();
        qw.eq("userId",userId);
        List<Friend> friendList = friendService.list(qw);
        List<Integer> uid=new ArrayList<>();
        for (Friend friend : friendList) {
            uid.add(friend.getUserFriend());
        }
        //根据已有id查询所有关注视频
        List<Releasetable> releasetableList = releasetableService.getReleasetableList(uid);
        for (Releasetable releasetable : releasetableList) {
            releasetable.setWorksCover("http://localhost:9000/star/"+releasetable.getWorksCover());
            //查询视频
            QueryWrapper<Releasevideos> videoQw=new QueryWrapper<>();
            videoQw.eq("releaseId",releasetable.getReleaseId());
            Releasevideos video = releasevideosService.getOne(videoQw);
            //查询评论数
            Integer num=commenttableService.getLastCommentCount(releasetable.getReleaseId());
            releasetable.setCommentNum(num);
            if(video!=null){
                video.setVideosSrc("http://localhost:9000/star/"+video.getVideosSrc());
                releasetable.setFrilmsg(video.getVideosSrc());
            }
        }
        return releasetableList;
    }
    /**
     * 首页推荐数据获取
     */
    @GetMapping("indexViode")
    public Object indexViode(Integer userId){
        List<Releasetable> list=new ArrayList<>();
        //查询视频
        if(userId!=null){
            list=releasetableService.getIndexList(userId);
        }else {
            list = releasetableService.list();
        }
        for(Releasetable releasetable:list){
            releasetable.setWorksCover("http://localhost:9000/star/"+releasetable.getWorksCover());
            //查询视频
            QueryWrapper<Releasevideos> videoQw=new QueryWrapper<>();
            videoQw.eq("releaseId",releasetable.getReleaseId());
            Releasevideos video = releasevideosService.getOne(videoQw);
            //查询评论数
            Integer num=commenttableService.getLastCommentCount(releasetable.getReleaseId());
            releasetable.setCommentNum(num);
            if(video!=null){
                video.setVideosSrc("http://localhost:9000/star/"+video.getVideosSrc());
                releasetable.setFrilmsg(video.getVideosSrc());
            }
        }
        List<Releasetable> releasetableList=new ArrayList<>();
        Random random=new Random();
        int num=list.size();
        //随机视频分配中
        while (true){
            if(releasetableList.size()==num){
                break;
            }
            int index=random.nextInt(list.size());
            if(releasetableList.size()>0){
                for (int j = 0; j < releasetableList.size(); j++) {
                    if(releasetableList.get(j)!=list.get(index)){
                        releasetableList.add(list.get(index));
                        list.remove(index);
                        break;
                    }
                }
            }else {
                releasetableList.add(list.get(index));
                list.remove(index);
            }
        }
        return releasetableList;
    }


    /**
     * 删除视频
     */
    @PostMapping("deleteMyViode")
    public Object deleteMyViode(@RequestBody Releasetable releasetable){
        QueryWrapper<Releasetable> qw=new QueryWrapper<>();
        qw.eq("releaseId",releasetable.getReleaseId());
        return releasetableService.remove(qw);
    }

    @PostMapping("delVideoByIds")
    public String delVideoByIds(@RequestBody List<Integer> ids){
        int i = releasetableService.delVideoByIds(ids);
        if (i>0){
            return "success";
        }else {
            return "fail";
        }
    }

    /**
     * 条件查询视频集合
     */
    @GetMapping("/selectAllVideo")
    public ResponseEntity getAllUser(Integer pageNo, Integer pageSize, String title, Integer classId, String userName) {
        pageNo=(pageNo-1)*pageSize;
        return releasetableService.videoConditionQuery(pageNo,pageSize,title,classId,userName);
    }

    @PostMapping("/updVideo")
    public String updVideoById(@RequestBody Releasetable releasetable){
        QueryWrapper<Releasetable> qw=new QueryWrapper<>();
        qw.eq("releaseId",releasetable.getReleaseId());
        boolean update = releasetableService.update(releasetable, qw);
        if (update){
            return "success";
        }else {
            return "fail";
        }

    }
}